package snake.model;

import snake.common.Constant;
import snake.common.GameContextHolder;
import snake.enums.Direction;
import snake.factory.FoodFactory;

import java.util.ArrayList;
import java.util.List;

public class Snake {
    public SnakeHead snakeHead;
    public List<SnakeBody> snakeBodyList = new ArrayList<>();

    public Snake() {
        snakeHead = new SnakeHead(Direction.RIGHT, 2 * Constant.GRID_SIZE, Constant.GRID_Y_COUNT / 2 * Constant.GRID_SIZE);
        snakeBodyList.add(new SnakeBody(Constant.GRID_SIZE, Constant.GRID_Y_COUNT / 2 * Constant.GRID_SIZE));
        snakeBodyList.add(new SnakeBody(0, Constant.GRID_Y_COUNT / 2 * Constant.GRID_SIZE));
    }

    public SnakeHead getSnakeHead() {
        return snakeHead;
    }

    public List<SnakeBody> getSnakeBodyList() {
        return snakeBodyList;
    }

    public void move() {

        // 蛇身体的移动
        for (int i = this.snakeBodyList.size() - 1; i >= 1; i--) {
            snakeBodyList.get(i).x = snakeBodyList.get(i - 1).x;
            snakeBodyList.get(i).y = snakeBodyList.get(i - 1).y;
        }
        snakeBodyList.get(0).x = snakeHead.x;
        snakeBodyList.get(0).y = snakeHead.y;

        // 蛇头的移动
        if (snakeHead.getDirection() == Direction.UP) {
            snakeHead.y -= Constant.GRID_SIZE;
        } else if (snakeHead.getDirection() == Direction.DOWN) {
            snakeHead.y += Constant.GRID_SIZE;
        } else if (snakeHead.getDirection() == Direction.LEFT) {
            snakeHead.x -= Constant.GRID_SIZE;
        } else if (snakeHead.getDirection() == Direction.RIGHT) {
            snakeHead.x += Constant.GRID_SIZE;
        }
    }

    public boolean isEatBody() {
        for (int i = this.snakeBodyList.size() - 1; i >= 1; i--) {
            if (snakeHead.x == snakeBodyList.get(i).x && snakeHead.y == snakeBodyList.get(i).y) {
                return true;
            }
        }
        return false;
    }

    public boolean isOutOfBound() {
        return snakeHead.x >= Constant.GRID_X_COUNT * Constant.GRID_SIZE ||
                snakeHead.y >= Constant.GRID_Y_COUNT * Constant.GRID_SIZE ||
                snakeHead.x < 0 || snakeHead.y < 0;
    }


    public void eatFood() {
        Integer newX = null;
        Integer newY = null;
        // 获取蛇身的最后一个元素
        SnakeBody lastBody = snakeBodyList.get(snakeBodyList.size() - 1);
        newX = lastBody.x;
        newY = lastBody.y;
        // 分数+1
        GameContextHolder.getContext().increaseScore();
        // move();
        // move结束后,新的bodyObj对象添加到bodyObjList
        snakeBodyList.add(new SnakeBody(newX, newY));
    }
}
